import Config from './config.js'

export default {
	/**
	 * 页面跳转
	 * @param {string} to 跳转链接 /pages/idnex/index
	 * @param {Object} param 参数 {key : value, ...}
	 * @param {string} mode 模式 
	 */
	redirectTo(to, param, urlType, mode) {
		let url = to;
		if (param != undefined) {
			Object.keys(param).forEach(function(key) {
				if (url.indexOf('?') != -1) {
					url += "&" + key + "=" + param[key];
				} else {
					url += "?" + key + "=" + param[key];
				}
			});
		}
		if (urlType == 'tabbar') {
			uni.switchTab({
				url: url
			})
		} else {
			switch (mode) {
				case 'redirectTo':
					// 关闭当前页面，跳转到应用内的某个页面。
					uni.redirectTo({
						url: url
					});
					break;
				case 'reLaunch':
					// 关闭所有页面，打开到应用内的某个页面。
					uni.reLaunch({
						url: url
					});
					break;
				default:
					// 保留当前页面，跳转到应用内的某个页面
					uni.navigateTo({
						url: url
					});
			}
		}
	},
	/**
	 * 图片路径转换
	 * @param {Object} img_path
	 */
	img(img_path) {
		var path = "";
		if (img_path != undefined && img_path != "") {
			if (img_path.indexOf("http://") == -1 && img_path.indexOf("https://") == -1) {
				path = Config.imgUrl + "/" + img_path;
			} else {
				path = img_path;
			}
		}
		return path;
	},
	/**
	 * 时间戳转日期格式
	 * @param {Object} timeStamp
	 */
	timeStampTurnTime(timeStamp) {
		if (timeStamp > 0) {
			var date = new Date();
			date.setTime(timeStamp * 1000);
			var y = date.getFullYear();
			var m = date.getMonth() + 1;
			m = m < 10 ? ('0' + m) : m;
			var d = date.getDate();
			d = d < 10 ? ('0' + d) : d;
			var h = date.getHours();
			h = h < 10 ? ('0' + h) : h;
			var minute = date.getMinutes();
			var second = date.getSeconds();
			minute = minute < 10 ? ('0' + minute) : minute;
			second = second < 10 ? ('0' + second) : second;
			return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
		} else {
			return "";
		}
	},
	/**
	 * 倒计时
	 * @param {Object} seconds 秒
	 */
	countDown(seconds) {
		let [day, hour, minute, second] = [0, 0, 0, 0]
		if (seconds > 0) {
			day = Math.floor(seconds / (60 * 60 * 24))
			hour = Math.floor(seconds / (60 * 60)) - (day * 24)
			minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
			second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
		}
		if (day < 10) {
			// day = '0' + day
		}
		if (hour < 10) {
			// hour = '0' + hour
		}
		if (minute < 10) {
			// minute = '0' + minute
		}
		if (second < 10) {
			// second = '0' + second
		}
		return {
			d: day,
			h: hour,
			i: minute,
			s: second
		};
	},
	/**
	 * 数值去重
	 * @param {Object} arr
	 */
	unique(arr) {
		return Array.from(new Set(arr))
	},
	/**
	 * 判断值是否在数组中
	 * @param {Object} elem
	 * @param {Object} arr
	 * @param {Object} i
	 */
	inArray: function(elem, arr) {
		return arr == null ? -1 : arr.indexOf(elem);
	},
	/**
	 * 获取某天日期
	 * @param {Object} day
	 */
	getDay: function(day) {
		var today = new Date();
		var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
		today.setTime(targetday_milliseconds);

		const doHandleMonth = function(month) {
			var m = month;
			if (month.toString().length == 1) {
				m = "0" + month;
			}
			return m
		}

		var tYear = today.getFullYear();
		var tMonth = today.getMonth();
		var tDate = today.getDate();
		var tWeek = today.getDay();
		var time = parseInt(today.getTime() / 1000);
		tMonth = doHandleMonth(tMonth + 1);
		tDate = doHandleMonth(tDate);

		const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
		return {
			't': time,
			'y': tYear,
			'm': tMonth,
			'd': tDate,
			'w': week[tWeek]
		};
	},


	/**
	 * 图片选择加上传
	 * @param number num
	 * @param {Object} params
	 * @param {Object} callback
	 * return array
	 */
	upload: function(num, params, callback) {
		var data = {
			token: uni.getStorageSync('token'),
			private_key: Config.privateKey
		}
		data = Object.assign(data, params);
		var imgs_num = num;
		var _self = this;
		uni.chooseImage({
			count: imgs_num,
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册或者拍照
			success: async function(res) {
				const tempFilePaths = res.tempFilePaths;
				var _data = data;
				var imgs = [];
				for (var i = 0; i < tempFilePaths.length; i++) {
					var path = await _self.upload_file_server(tempFilePaths[i], _data);
					imgs.push(path);
				}
				typeof callback == 'function' && callback(imgs);
			}
		});
	},
	//上传
	upload_file_server(tempFilePath, data) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: Config.baseUrl + '/api.php?method=System.Upload.uploadImage',
				filePath: tempFilePath,
				name: 'filePath',
				formData: data,
				success: function(res) {
					var path_str = JSON.parse(res.data);
					var path = JSON.parse(path_str);
					if (path.data.code == 1) {
						resolve(path.data.data);
					} else {
						reject("error");
					}
				}
			});

		});

	},


	/**
	 * 复制
	 * @param {Object} message
	 * @param {Object} callback
	 */
	copy(value, callback) {
		var oInput = document.createElement('input'); //创建一个隐藏input（重要！）
		oInput.value = value; //赋值
		document.body.appendChild(oInput);
		oInput.select(); // 选择对象
		document.execCommand("Copy"); // 执行浏览器复制命令
		oInput.className = 'oInput';
		oInput.style.display = 'none';

		typeof callback == 'function' && callback();
	},
	/**
	 * 是否是微信浏览器
	 */
	isWeiXin() {
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
			return true;
		} else {
			return false;
		}
	},
	//显示消息提示框
	showToast(params = {}) {

		params.title = params.title || "";
		params.icon = params.icon || "none";
		params.position = params.position || 'bottom';
		uni.showToast(params);
	}
	/**
	 * 将图片格式转换为base64 适应微信小程序
	 */
	// ifdef MP-WEIXIN
	// picConversion(tempFilePaths){
	// 	for(let i = 0; i < tempFilePaths.length; i++){
	// 		wx.getFileSystemManager().readFile({
	// 			filePath: tempFilePaths[i], //图片路径
	// 			encoding: 'base64', //图片格式转换
	// 		})
	// 	}
	// }
	// endif
}
